#!/usr/bin/env python



import os
import sys
import itertools

def main():
    assets_root = sys.argv[1]
    assert os.path.isdir(assets_root)
    output_dir = sys.argv[2]
    assert os.path.isdir(output_dir)

    assets = [
        os.path.relpath(os.path.join(root, path), assets_root)
        for root, __, paths in os.walk(assets_root)
        for path in paths
    ]

    cc_out = open(os.path.join(output_dir, "web_assets.cc"), "w")
    rc_out = open(os.path.join(output_dir, "web_assets.rc"), "w")

    cc_out.write(cc_prelude)
    rc_out.write(rc_prelude)

    cc_out.write("std::map<std::string, const std::string> static_web_assets = {\n")

    relpath = os.path.relpath(assets_root, output_dir).replace("/","\\\\")

    for i, asset in enumerate(assets):
        id = 1000 + i
        cc_out.write("""    { "/%s", find_asset(%d) },\n""" % (asset, id))
        rc_out.write("""%d RCDATA "%s\\\\%s"\n""" % (id, relpath, asset.replace("/","\\\\")))

    cc_out.write("};")

cc_prelude = """
// Generated by scripts/build-web-assets-rc.py

#include <map>
#include <string>

#include "windows.hpp"
#include "errors.hpp"

std::string find_asset(int id) {
    HRSRC res = FindResource(NULL, MAKEINTRESOURCE(id), RT_RCDATA);
    guarantee_winerr(res != nullptr, "FindResource failed");
    unsigned int size = SizeofResource(NULL, res);
    guarantee_winerr(size != 0, "SizeofResource failed");
    HGLOBAL data = LoadResource(NULL, res);
    guarantee_winerr(data != nullptr, "LoadResource failed");
    const void* ptr = LockResource(data);
    guarantee_winerr(ptr != nullptr, "LockResource failed");
    return std::string(static_cast<const char*>(ptr), size);
}
"""

rc_prelude = """
// Generated by scripts/build-web-assets-rc.py
"""

if __name__ == "__main__":
    main()
